import actionsType from "./actionsType"

const initState = {
  list: [],
  car: []
}

const reducer = (state = initState, action) => {
  const { type, payload } = action
  let { car } = state
  switch(type) {
    case actionsType.SET_LIST:
      return {
        ...state,
        list: payload
      };
    // 加入购物车
    case actionsType.ADD_CAR_ITEM: 
      // 去重复
    const item = car.find(v => v.id === payload.id)
    // 存在
    if(item) {
      // 数量+
      item.count++
    } else {
      // 不存在 推入
      car.push({
        ...payload,
        count: 1,
        checked: false
      })
    }
    console.log('加入购物车后的数据为：', car);
      return {
        ...state,
        car: [...car]
      };
    // 减少购物车
    case actionsType.SUB_CAR_ITEM: 
    // 找到购物车数据
      const Subitem = car.find(v => v.id === payload.id)
      // 判断数量是否小于等于1
      if(Subitem.count <= 1) {
        // 直接删除购物车数据
        car =  car.filter(v => v.id !== payload.id)
      } else {
        // 数量减少
        Subitem.count--
      }
      return {
        ...state,
        car: [...car]
      };
    // 全选切换
    case actionsType.SWITCH_ALL_CAR_ITEM:
      // 让每一个单选的状态 等于 传递过来的全选状态
      car.forEach(v => {
        v.checked = payload.checked
      })
      return {
        ...state,
        car: [...car]
      };
    // 单选切换
    case actionsType.SWITCH_CAR_ITEM:
      // 找到购物车数据
      const oneItem = car.find(v => v.id === payload.id)
      // 切换单选状态 自身取反
      oneItem.checked = !oneItem.checked
      return {
        ...state,
        car: [...car]
      }
    default: 
      return {
        ...state
      }
  }
}

export default reducer